<template>
  <div class="card-container" v-auth="'parking:card:list'">
    <!-- 搜索区域 -->
    <div class="search-container">
      <span class="search-label">车牌号码：</span>

      <el-input
        clearable
        placeholder="请输入内容"
        v-model="params.carNumber"
        class="search-main"
      />
      <span class="search-label">车主姓名：</span>

      <el-input
        clearable
        placeholder="请输入内容"
        v-model="params.personName"
        class="search-main"
      />
      <span class="search-label">状态：</span>

      <el-select v-model="params.cardStatus">
        <el-option
          v-for="item in cardStatusList"
          :value="item.id"
          :label="item.name"
          :key="item.id"
        />
      </el-select>

      <el-button type="primary" class="search-btn" @click="doSearch" v-auth-btn="'parking:card:list'"
        >查询</el-button
      >
    </div>

    <!-- 新增删除操作区域 -->
    <div class="create-container">
      <el-button type="primary" @click="addCard" v-auth-btn="'parking:card:add_edit'"> 添加月卡</el-button>

      <el-button @click="deleteSelectedCard" v-auth-btn="'parking:card:remove'">批量删除</el-button>
    </div>

    <!-- 表格区域 -->
    <div class="table">
      <el-table
        style="width: 100%"
        :data="rows"
        @selection-change="handleSelection">

        <el-table-column type="selection" width="50" />
        <el-table-column type="index" label="序号" prop="id" width="60" />
        <el-table-column label="车主名称" prop="personName" />
        <el-table-column label="联系方式" prop="phoneNumber" />
        <el-table-column label="车牌号码" prop="carNumber" />
        <el-table-column label="车辆品牌" prop="carBrand" />
        <el-table-column label="剩余有效天数" prop="totalEffectiveDate" />
        <el-table-column label="状态" prop="cardStatus">
          <!-- :formatter="formatStatus" -->
          <template slot-scope="scope">
            <el-tag :type="scope.row.cardStatus === 0 ? 'success' : 'danger'">{{
              formatStatus(scope.row)
            }}</el-tag>
          </template>
        </el-table-column>
        <el-table-column label="操作" fixed="right" width="240">
          <template #default="scope">
            <el-button size="mini" type="text" v-auth-btn="'parking:card:recharge'">续费</el-button>
            <el-button size="mini" type="text" @click="lookData(scope.row.id)" v-auth-btn="'parking:card:query'"
              >查看</el-button>
            <el-button size="mini" type="text" @click="editData(scope.row.id)" v-auth-btn="'parking:card:add_edit'"
              >编辑</el-button>
            <el-button type="text" size="mini" @click="deleteData(scope.row.id)" v-auth-btn="'parking:card:remove'"
              >删除</el-button>
          </template>
        </el-table-column>
      </el-table>
    </div>

    <div class="page-container">
      <el-pagination
        layout="total,sizes,prev, pager, next,jumper"
        :total="total"
        :current-page="currentPage"
        :page-size="pageSize"
        :page-sizes="pageSizes"
        @current-change="handleCurrentChange"
        @size-change="handleSizeChange"
        background
      />
    </div>

    <el-dialog :title="title" width="580px" :visible="isshow" @close="close">
      <div class="form-container">
        <el-form
          :model="carInfoForm"
          :rules="rules"
          label-width="100px"
          ref="carInfoForm"
        >
          <el-form-item label="车主姓名" prop="personName">
            <el-input v-model="carInfoForm.personName" />
          </el-form-item>
          <el-form-item label="联系方式" prop="phoneNumber">
            <el-input v-model="carInfoForm.phoneNumber" />
          </el-form-item>

          <el-form-item label="车牌号码" prop="carNumber">
            <el-input v-model="carInfoForm.carNumber" />
          </el-form-item>

          <el-form-item label="车辆品牌" prop="carBrand">
            <el-input v-model="carInfoForm.carBrand" />
          </el-form-item>
        </el-form>
        <el-form
          :model="feeForm"
          :rules="feeFormRules"
          label-width="100px"
          ref="feeForm"
        >
          <el-form-item label="有效日期" prop="payTime">
            <el-date-picker
              v-model="feeForm.payTime"
              type="daterange"
              range-separator="至"
              start-placeholder="开始日期"
              end-placeholder="结束日期"
            />
          </el-form-item>

          <el-form-item label="支付金额" prop="paymentAmount">
            <el-input v-model="feeForm.paymentAmount" />
          </el-form-item>

          <el-form-item label="支付方式" prop="paymentMethod">
            <el-select v-model="feeForm.paymentMethod">
              <el-option
                v-for="item in payMethodList"
                :key="item.id"
                :value="item.id"
                :label="item.name"
              />
            </el-select>
          </el-form-item>
        </el-form>
      </div>
      <template #footer>
        <el-button size="mini" @click="close">取 消</el-button>
        <el-button size="mini" type="primary" @click="submit">确 定</el-button>
      </template>
    </el-dialog>
    
  </div>
</template>


<script>
import {
  getCardList,
  addCard,
  deleteCard,
  getEditCard,
  editCard,
  SelectDeleteCard,
} from "@/api/card";
export default {
  data() {
    return {
      selectedCarList: [],
      title: "添加月卡",
      total: 0,
      carInfoId: "",
      rechargeId: "",
      currentPage: 1,
      pageSize: 10,
      pageSizes: [5, 10, 20, 30],
      rows: [],
      isshow: false,
      cardStatusList: [
        {
          id: null,
          name: "全部",
        },
        {
          id: 0,
          name: "可用",
        },
        {
          id: 1,
          name: "已过期",
        },
      ],
      params: {
        cardStatus: "",
        carNumber: "",
        personName: "",
      },
      carInfoForm: {
        personName: "",
        phoneNumber: "",
        carNumber: "",
        carBrand: "",
      },
      feeForm: {
        paymentAmount: null,
        payTime: 0,
        paymentMethod: "",
      },
      rules: {
        personName: [
          {
            required: true,
            message: "请输入车主姓名",
            trigger: "blur",
          },
        ],
        phoneNumber: [
          {
            required: true,
            pattern: /^1[3-9]\d{9}$/,
            message: "请输入正确格式的号码",
            trigger: "blur",
          },
        ],
        carNumber: [
          {
            required: true,
            min: 8,
            max: 8,
            message: "请输入正确的八位车牌号",
            trigger: "blur",
          },
        ],
        carBrand: [
          {
            required: true,
            message: "请输入车辆品牌",
            trigger: "blur",
          },
        ],
      },
      // 缴费规则
      feeFormRules: {
        payTime: [
          {
            required: true,
            message: "请选择支付时间",
          },
        ],
        paymentAmount: [
          {
            required: true,
            message: "请输入支付金额",
            trigger: "blur",
          },
        ],
        paymentMethod: [
          {
            required: true,
            message: "请选择支付方式",
            trigger: "change",
          },
        ],
      },
      // 支付方式列表
      payMethodList: [
        {
          id: "Alipay",
          name: "支付宝",
        },
        {
          id: "WeChat",
          name: "微信",
        },
        {
          id: "Cash",
          name: "线下",
        },
      ],
    };
  },
  created() {
    this.getCardList()
  },
  methods: {
    doSearch() {
      this.getCardList()
    },
    deleteSelectedCard() {
      if (this.selectedCarList.length === 0) {
        this.$message({
          type: "warning",
          message: "请选择要删除的月卡",
        });
        return;
      }
      this.$confirm("此操作将永久删除选中的月卡, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(async () => {
          let res = await SelectDeleteCard(
            this.selectedCarList.map((item) => item.id)
          );
          this.getCardList();
          this.$message({
            type: "success",
            message: res.msg,
          });
        })
        .catch((error) => {
          console.log(error);
        });
    },
    handleSelection(rowList) {
      console.log(rowList);
      this.selectedCarList = rowList;
    },
    async editData(id) {
      this.title = "编辑月卡";
      let res = await getEditCard(id);
      this.isshow = true;
      const {
        carInfoId,
        rechargeId,
        cardStartDate,
        cardEndDate,
        paymentAmount,
        paymentMethod,
        personName,
        phoneNumber,
        carNumber,
        carBrand,
      } = res.data;
      this.feeForm = {
        paymentAmount,
        paymentMethod,
        payTime: [cardStartDate, cardEndDate],
      };
      this.carInfoForm = {
        personName,
        phoneNumber,
        carNumber,
        carBrand,
      };
      this.rechargeId = rechargeId;
      this.carInfoId = carInfoId;
    },
    deleteData(id) {
      this.$confirm("此操作将永久删除该月卡, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(async () => {
          let res = await deleteCard(id);
          this.$message({
            type: "success",
            message: res.msg
          });
          this.getCardList()
        })
        .catch((error) => {
          console.log(error)
        })
    },
    async getCardList() {
      const param = {
        page: this.currentPage,
        pageSize: this.pageSize,
        ...this.params
      };
      const { data } = await getCardList(param)
      this.rows = data.rows;
      this.total = data.total;
    },
    submit() {
      this.isshow = true;
      this.$refs.carInfoForm.validate((valid) => {
        if (valid) {
          this.$refs.feeForm.validate(async (valid) => {
            if (valid) {
              const payload = {
                ...this.feeForm,
                ...this.carInfoForm,
                cardStartDate: this.feeForm.payTime[0],
                cardEndDate: this.feeForm.payTime[1],
              };
              delete payload.payTime;
              try {
                if (this.title === "编辑月卡") {
                  payload.rechargeId = this.rechargeId;
                  payload.carInfoId = this.carInfoId;
                  console.log(payload);
                  await editCard(payload);

                  this.$message.success("编辑卡成功");
                  this.getCardList();
                } else {
                  await addCard(payload);
                  this.$message.success("添加卡成功");
                  this.getCardList();
                }
                this.close();
              } catch (e) {
                this.$message.error(e.response?.data?.message || "修改卡失败");
              }
            }
          });
        }
      });
    },
    close() {
      this.isshow = false;
      this.$refs.feeForm.resetFields();
      this.$refs.carInfoForm.resetFields();
      // Clear form data
      this.carInfoForm = {
        personName: "",
        phoneNumber: "",
        carNumber: "",
        carBrand: "",
      };
      this.feeForm = {
        paymentAmount: null,
        payTime: 0,
        paymentMethod: "",
      };
    },
    addCard() {
      this.isshow = true;
      this.title = "添加月卡";
    },
    handleCurrentChange(current) {
      this.currentPage = current;
      this.getCardList();
    },
    handleSizeChange(size) {
      this.pageSize = size;
      this.getCardList();
    },
    formatStatus(row) {
      const MAP = {
        0: "可用",
        1: "已过期",
      };
      return MAP[row.cardStatus];
    },
  },
};
</script>


<style lang="scss" scoped>
.card-container {
  padding: 20px;
  background-color: #fff;
}

.search-container {
  display: flex;
  align-items: center;
  border-bottom: 1px solid rgb(237, 237, 237, 0.9);
  padding-bottom: 20px;
  .search-main {
    width: 220px;
    margin-right: 10px;
  }
  .search-btn {
    margin-left: 20px;
  }
}
.create-container {
  margin: 10px 0px;
}
.page-container {
  padding: 4px 0px;
  text-align: right;
}
.form-container {
  padding: 0px 80px;
}
</style>
